import { ConstantEnum } from '@libs/common/enums';
import { getConfig } from '@libs/common/utils';
import { Provider } from '@nestjs/common';
import { Dayjs, FormatDateTime } from '@shencom/utils-date';
import { utilities, WinstonModule } from 'nest-winston';
import winston from 'winston';
import { Console } from 'winston/lib/winston/transports';
import DailyRotateFile from 'winston-daily-rotate-file';

const { LOG } = getConfig();

function createDailyRotateTransport(level: string, filename: string) {
  return new DailyRotateFile({
    level,
    dirname: 'logs',
    filename: `${filename}-%DATE%.log`,
    datePattern: 'YYYY-MM-DD-HH',
    zippedArchive: true,
    maxSize: '20m',
    maxFiles: '7d',
    format: winston.format.combine(
      winston.format.timestamp({
        format: () => FormatDateTime(Dayjs().valueOf(), 'YYYY/MM/DD HH:mm:ss'),
      }),
      winston.format.simple(),
    ),
  });
}

export const LoggerProviders: Provider = {
  provide: ConstantEnum.WINSTON_LOGGER_TOKEN,
  useFactory: () => {
    const combine: winston.Logform.Format[] = [];
    combine.push(winston.format.timestamp());
    combine.push(utilities.format.nestLike());
    const consoleTransports = new Console({
      level: LOG.level || 'info',
      format: winston.format.combine(...combine),
    });

    return WinstonModule.createLogger({
      transports: [
        consoleTransports,
        ...(LOG.enable
          ? [
              createDailyRotateTransport('info', 'info'),
              createDailyRotateTransport('warn', 'warn'),
              createDailyRotateTransport('error', 'error'),
            ]
          : []),
      ],
    });
  },
};
